package dao;

import java.util.List;

import javax.faces.context.FacesContext;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;

import modelo.Imovel;

public class ImovelDao extends GenericJPADao<Imovel> {

	public ImovelDao(){
		this.persistenceClass = Imovel.class;
	}
	
	/*public boolean cadastrar(Imovel imovel) {
		em.getTransaction().begin();

		try {
			em.persist(imovel);
			em.getTransaction().commit();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
*/
	/*public Imovel buscar(int id) {
		Imovel imovel = em.find(Imovel.class, id);
		return imovel;
	}*/

	/*public boolean atualizar(Imovel imovel) {
		em.getTransaction().begin();

		try {
			// funcao para fazer o update do imovel
			em.merge(imovel);
			em.getTransaction().commit();
			return true;

		} catch (Exception e) {
			return false;
		}

	}*/

	/*
	 * public List<Imovel> getLista(){ Query query =
	 * em.createQuery("select i from Imovel i"); return
	 * (List<Imovel>)query.getResultList(); }
	 */
	public List<Imovel> getLista() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		Query query = em.createNamedQuery("Imovel.listaImoveis");
		String email = (String) session.getAttribute("email");
		if (email == null)
			email = "";
		query.setParameter("email", email);
		return (List<Imovel>) query.getResultList();
	}

	/*public boolean excluir(int id) {
		Imovel imovel = find(id);
		em.getTransaction().begin();
		em.remove(imovel);
		em.getTransaction().commit();

		return true;
	}*/

	// junior
	public List<Imovel> getListIndex(Imovel imovel) {

		Query query = em.createNamedQuery("Imovel.listaIndex");

		return query.getResultList();
	}

	// junior

	public List<Imovel> getListParametro(Imovel imovel) {

		if (imovel.getCidade() == null)
			imovel.setCidade("");
		if (imovel.getQtdQuartos() == null)
			imovel.setQtdQuartos(0);
		if (imovel.getQtdBanheiros() == null)
			imovel.setQtdBanheiros(0);

		Query query = em.createNamedQuery("Imovel.listaParametros");
		query.setParameter("cidade", imovel.getCidade());
		query.setParameter("qnt_quartos", imovel.getQtdQuartos());
		query.setParameter("quant_banheiros", imovel.getQtdBanheiros());
		query.setParameter("garagem", imovel.getGaragem());

		return query.getResultList();
	}

	public List<String> getListCidades() {

		Query query = em.createNamedQuery("Imovel.listaCidades");

		return query.getResultList();
	}

	public static void main(String[] args) {

		ImovelDao dao = new ImovelDao();

		Imovel imovel = new Imovel();
		imovel.setCidade(null);
		imovel.setQtdQuartos(null);
		imovel.setQtdBanheiros(null);
		imovel.setGaragem(true);

		for (Imovel i : dao.getListParametro(imovel)) {
			System.out.println(i.getRua());
		}

	}

}
